import os
import logging
from qcloud_cos import CosConfig, CosS3Client

# 腾讯云SecretId
TENCENT_SECRET_ID = os.getenv("TENCENT_SECRET_ID")
# 腾讯云SecretKey
TENCENT_SECRET_KEY = os.getenv("TENCENT_SECRET_KEY")
# 腾讯云存储区域
TENCENT_REGION = os.getenv("TENCENT_REGION")
# 腾讯云存储桶名称
TENCENT_BUCKET = os.getenv("TENCENT_BUCKET")

TENCENT_TOKEN = None
TENCENT_SCHEME = "https"


def upload_to_cos(file, key):
    config = CosConfig(
        Region=TENCENT_REGION,
        SecretId=TENCENT_SECRET_ID,
        SecretKey=TENCENT_SECRET_KEY,
        Token=TENCENT_TOKEN,
        Scheme=TENCENT_SCHEME,
    )
    client = CosS3Client(config)
    client.put_object(
        Bucket=TENCENT_BUCKET,
        Body=file.stream,  # 这是用户表单上传的文件的二进制文件流
        Key=key,
        StorageClass="STANDARD",
        EnableMD5=False,
    )
    image_url = (
        f"{TENCENT_SCHEME}://{TENCENT_BUCKET}.cos.{TENCENT_REGION}.myqcloud.com/{key}"
    )
    return image_url
